<?php
namespace addons\yexam\service;

use app\admin\model\yexam\Answer;
use app\admin\model\yexam\Fav;
use app\admin\model\yexam\Question;
use app\admin\model\yexam\QuestionLog;
use think\Exception;

class Library
{

    public $model;

    public function __construct()
    {
        $this->model = new \app\admin\model\yexam\Library();
    }

    /**
     * 获取历年真题列表
     * @param $page
     * @param $limit
     * @throws \think\Exception
     */
    public function getLibraryList($subject_id,$page,$limit,$ids){
        $count = $this->model->where(['status'=>1,'subject_id'=>$subject_id])->count();
        if($page){
            $data = $this->model->field("id,library_name as name,question_ids")->where('id','in',$ids)->where(['status'=>1,'subject_id'=>$subject_id])->page($page,$limit)->order("weigh asc")->select();
        }else{
            $data = $this->model->field("id,library_name as name,question_ids")->where('id','in',$ids)->where(['status'=>1,'subject_id'=>$subject_id])->order("weigh asc")->select();
        }
        return ['total'=>$count,'data'=>$data];
    }

    /**
     * 获取历年真题答题卡
     */
    public function getCard($library_id,$user_id){

        $libraryInfo = $this->model->where(['id'=>$library_id])->find();
        if(empty($libraryInfo)){
            return;
        }

        $questionModel = new \app\admin\model\yexam\Question();
        $data = $questionModel
            ->alias("question")
            ->field("question.*,ifnull(log.state,3) as state")
            ->join("yexam_question_log log","question.id=log.question_id and log.user_id=".$user_id,"left")
            ->where(['question.id'=>['in',$libraryInfo['question_ids']]])->order("question.type asc,question.id asc")->select();

        $return = [];
        foreach($data as $v){
            $_return['id'] = $v['id'];
            $_return['state'] = $v['state'] ==3?3:($v['state']==0?1:2);        //1是错2是对3是未答过此题

            $return[] = $_return;

        }

        return $return;
    }

    /**
     * 获取章节练习错题答题卡
     */
    public function  getFavCard($library_id,$user_id){
        $favModel = new Fav();
        $data = collection($favModel
            ->alias("fav")
            ->field("question.id")
            ->join("yexam_question question","fav.question_id=question.id",'inner')
            ->join("yexam_library library","fav.library_id=library.id",'inner')
            ->where(['fav.library_id'=>$library_id,'fav.user_id'=>$user_id])
            ->order("question.type asc,question.id asc")
            ->select());

        return $data;
    }



    /**
     * 获取历年真题错题答题卡
     */
    public function  getErrorCard($library_id,$user_id){
        $logModel = new QuestionLog();
        $data = collection($logModel
            ->alias("log")
            ->field("question.id")
            ->join("yexam_question question","log.question_id=question.id",'inner')
            ->join("yexam_library library","log.library_id=library.id",'inner')
            ->where(['log.library_id'=>$library_id,'log.user_id'=>$user_id,'log.state'=>0])
            ->order("question.type asc,question.id asc")
            ->select());

        return $data;
    }

    /**
     * 移除历年真题错题
     * @param $unit_id
     * @param $id
     * @param $user_id
     */
    public function removeErrorQuestion($id,$user_id){
        $logModel = new QuestionLog();
        $row = $logModel
            ->where(['library_id'=>['neq',0],'user_id'=>$user_id,'question_id'=>$id,'state'=>0])
            ->find();
        if(empty($row)){
            return true;
        }
        $row->delete();
        return true;
    }


    /**
     * 获取上次答题定位num
     */
    public function getLastPosition($library_id,$user_id){

        //获取当前单元已经练习的最后的题目ID
        $logModel = new QuestionLog();
        $data = $logModel
            ->field("a.question_id")
            ->alias("a")
            ->join("yexam_question b","a.question_id=b.id",'inner')
            ->where(['a.library_id'=>$library_id,'user_id'=>$user_id])->order('a.lasttime desc')->find();
        if(empty($data)){
            return 1;
        }else{
            $questionModel = new \app\admin\model\yexam\Question();
            $questionList = $questionModel->field("id")->where(['library_id'=>$library_id])->order("type asc,id asc")->select();
            $num = 1;
            foreach($questionList as $k=>$v){
                $num++;
                if($data['question_id'] == $v['id']){
                    break;
                }
                
            }
            if($num>count($questionList)){
                $num = 1;
            }
            return $num;
        }
    }

    /**
     * 历年真题答题
     */
    public function doanswer($id,$answer,$user_id,$typeId){
        $questionModel = new \app\admin\model\yexam\Question();
        if($questionInfo = $questionModel->where(['id'=>$id])->find()){
            if (preg_replace('# #', '', $questionInfo['right_answer']) != preg_replace('# #', '', $answer)) {
                $result = 0;
            }else{
                $result = 1;
            }
        }else{
            return;
        }
        //写入答题记录
        $logModel = new QuestionLog();
        if($log = $logModel->where(['question_id'=>$id,'user_id'=>$user_id])->find()){
            $log->save(['lasttime'=>time(),'state'=>$result]);
            $log->setInc('total_num');
            if(empty($result)){
                $log->setInc('error_num');
            }else{
                $log->save(['error_num'=>0]);
            }
        }else{
            $library = new \app\admin\model\yexam\Library();
            $logModel = new QuestionLog();
            $logModel->save([
                'subject_id'=>$questionInfo['subject_id'],
                'library_id'=>$questionInfo['library_id'],
                'question_id'=>$id,
                'user_id'=>$user_id,
                'createtime'=>time(),
                'lasttime'=>time(),
                'state'=>$result,
                'type' => 4,
                "type_id" => $typeId,
                "user_answer" => $answer
            ]);
        }

        return $result;
    }

    /**
     * 获取历年真题错题列表
     */
    public function getErrorLogList($subject_id,$user_id,$page,$limit){
        $logModel = new QuestionLog();
        $count = $logModel
            ->alias("log")
            ->join("yexam_library library","log.library_id=library.id",'inner')
            ->where(['log.subject_id'=>$subject_id,'log.library_id'=>['neq',0],'log.user_id'=>$user_id,'log.state'=>0])->group("library.id")->count();
        if($page){
            $data = $logModel
                ->alias("log")
                ->field("library.id,library.library_name,count(log.id) as error_num")
                ->join("yexam_library library","log.library_id=library.id",'inner')
                ->where(['log.subject_id'=>$subject_id,'library_id'=>['neq',0],'log.user_id'=>$user_id,'log.state'=>0])
                ->page($page,$limit)
                ->group("library.id")
                ->select();
        }else{
            $data = $logModel
                ->alias("log")
                ->field("library.id,library.library_name,count(log.id) as error_num")
                ->join("yexam_library library","log.library_id=library.id",'inner')
                ->where(['log.subject_id'=>$subject_id,'library_id'=>['neq',0],'log.user_id'=>$user_id,'log.state'=>0])
                ->group("library.id")
                ->select();
        }

        return ['total'=>$count,'data'=>$data];
    }


    /**
     * 获取当前题库的题目数量
     * @throws Exception
     */
    public function getLibraryQuestionCount($libraryInfo){
        $questionModel = new Question();
        return $questionModel->where(['id'=>['in',$libraryInfo['question_ids']]])->count();
    }



    /**
     * 获取指定历年真题下的题目数量
     * @throws Exception
     */
    public function getLibraryQuestionTestNum($libraryInfo,$user_id){

        $questionModel = new Question();
        return $questionModel
            ->alias("question")
            ->join("yexam_question_log log","question.id=log.question_id","inner")
            ->where(['question.id'=>['in',$libraryInfo['question_ids']],"log.user_id"=>$user_id])->count();
    }

    /**
     * 获取指定历年真题下的题目正确数量
     * @throws Exception
     */
    public function getLibraryQuestionRightNum($libraryInfo,$user_id){

        $questionModel = new Question();
        return $questionModel
            ->alias("question")
            ->join("yexam_question_log log","question.id=log.question_id","inner")
            ->where(['question.id'=>['in',$libraryInfo['question_ids']],"log.state"=>1,"log.user_id"=>$user_id])->count();
    }

    /**
     * 获取题库正确率
     * @throws Exception
     */
    public function right_scale($libraryInfo,$user_id){
        //获取正确数量
        $test_num = self::getLibraryQuestionTestNum($libraryInfo,$user_id);
        $right_num = self::getLibraryQuestionRightNum($libraryInfo,$user_id);

        return empty($test_num)?0:(bcdiv($right_num,$test_num,2)*100);
    }


    /**
     * 获取章节练习收藏列表
     */
    public function getFavList($subject_id,$user_id,$page,$limit){
        $favModel = new Fav();
        $count = $favModel
            ->alias("fav")
            ->join("yexam_library library","fav.library_id=library.id",'inner')
            ->where(['library.subject_id'=>$subject_id,'fav.user_id'=>$user_id])
            ->count();

        if($page){
            $data = $favModel
                ->alias("fav")
                ->field("library.id,library.library_name,count(fav.id) as num")
                ->join("yexam_library library","fav.library_id=library.id",'inner')
                ->where(['library.subject_id'=>$subject_id,'fav.user_id'=>$user_id])
                ->group("library.id")
                ->page($page,$limit)
                ->select();
        }else{
            $data = $favModel
                ->alias("fav")
                ->field("library.id,library.library_name,count(fav.id) as num")
                ->join("yexam_library library","fav.library_id=library.id",'inner')
                ->where(['library.subject_id'=>$subject_id,'fav.user_id'=>$user_id])
                ->group("library.id")
                ->select();
        }

        return ['total'=>$count,'data'=>$data];
    }


}